<?php

namespace app\common\func;

use app\admin\model\AuthGroup;
use app\admin\model\Question;
use app\common\model\Address;
use app\common\model\Banner;
use app\common\model\FlowInfo;
use app\common\model\Gift;
use app\common\model\GiftApply;
use app\common\model\GiftCount;
use app\common\model\GiftOrder;
use app\common\model\Product;
use app\common\model\ProductApply;
use app\common\model\QuestionContent;
use app\common\model\ServiceLog;
use app\common\model\Terminal;
use app\common\model\TerminalApply;
use app\common\model\TerminalDetail;
use app\common\model\User;
use app\common\model\UserCard;
use app\common\model\YsInfo;
use think\Db;

class Lib
{

    public static function getUserCard($userId){
        return UserCard::where(['sale_id' => $userId])->field("real_name,real_idcard")->find();
    }

    public static function getSaleUserList()
    {
        return User::where(['is_typs' => 5, 'status' => 'normal'])->select();
    }

    public static function getGiftOrderBySn($sn)
    {
        return GiftOrder::where(['sn' => $sn])->find();
    }

    public static function getUserByAdmin($adminId)
    {
        return User::where(['admin_id' => $adminId])->find();
    }

    public static function getGiftByCode($code)
    {
        return Gift::where(['code' => $code])->find();
    }

    public static function getSaleGiftCount($adminId, $giftId)
    {
        return GiftCount::where(['admin_id' => $adminId, 'gift_id' => $giftId])->find();
    }

    public static function getGiftApplyById($applyId)
    {
        return GiftApply::get($applyId);
    }

    public static function getGiftApplyList($userId)
    {
        $user = self::getUserById($userId);
        $query = Db::name("gift_apply")->alias("g")
            ->join("admin a", "g.admin_id = a.id", "left")
            ->join("gift b", "g.gift_id = b.id", "left");

        if ($user->group_id == Constant::$masterGroup) {
            $query->where(['g.status' => ['>', 0]]);
        }
        $sale = Tools::getGroupTree(Constant::$masterGroup, 4);
        if (count($sale) > 0 && in_array($user->group_id, $sale)) {
            $query->where(['admin_id' => $user->admin_id]);
        }

        return $query->field("g.*,a.nickname,b.name,b.image,b.code,FROM_UNIXTIME(g.create_time, '%Y-%m-%d %H:%i:%s') as create_time")->select();
    }

    public static function getGiftById($giftId)
    {
        return Gift::get($giftId);
    }

    public static function getTerminalCount($type, $adminId)
    {
        switch ($type) {
            case 3:
                $msg = "绑定终端";
                $count = Db::name('terminal_apply')->alias("t")
                    ->join("terminal_detail d", "t.id = d.apply_id", "left")
                    ->where(['t.status' => 3, 'd.status' => 2, 't.admin_id' => $adminId])
                    ->count();
                break;
            case 4:
                $msg = "申请终端";
                $count = TerminalApply::where(['status' => 1])->sum("number");
                break;
            case 5:
                $msg = "客户反馈";
                $count = QuestionContent::where(['process' => 2])->count();
                break;
            default:
                $msg = "暂无信息";
                $count = 0;
        }
        return [$msg, $count];
    }

    public static function getApplyCount($type, $adminId)
    {
        $query = ProductApply::where(['status' => 1]);
        switch ($type) {
            case 3:
                $query->where(['confirm_time' => ['>', 0], "admin_id" => $adminId]);
                break;
            case 4:
                $query->where(['confirm_time' => ['>', 0]]);
                break;
            case 5:
                $query->where(['confirm_time' => 0]);
                break;
            default:
                return 0;
        }
        return $query->count();
    }

    public static function getGroup($groupId)
    {
        return AuthGroup::get($groupId);
    }

    public static function getTerminalApplyById($applyId)
    {
        return TerminalApply::get($applyId);
    }

    public static function getSaleList()
    {
        $sale = Tools::getGroupTree(Constant::$masterGroup, 4);
        return User::where(['group_id' => ['in', $sale]])->field("id,group_id,nickname,mobile")->select();
    }

    public static function getTerminalDetail($applyId, $sn)
    {
        return TerminalDetail::where(['apply_id' => $applyId, "sn" => $sn])->find();
    }

    public static function getTerminalSale($sn)
    {
        return Db::name("terminal_apply")->alias("a")
            ->join("terminal_detail d", "a.id = d.apply_id", "left")
            ->where(['d.sn' => $sn])
            ->field("a.*,d.sn")
            ->find();
    }

    public static function getTerminalApplyDetail($applyId)
    {
        $query = TerminalApply::alias("t")
            ->join("product p", "t.product_id = p.id", "left")
            ->join("admin a", "t.admin_id = a.id", "left")
            ->where(['t.status' => [">", 0]]);

        $query->where(['t.id' => $applyId]);

        return $query->field("t.*,p.id as product_id,p.name,a.nickname")->select();
    }

    public static function getTerminalApplyList($user)
    {
        $query = TerminalApply::alias("t")
            ->join("product p", "t.product_id = p.id", "left")
            ->join("admin a", "t.admin_id = a.id", "left");

        $groupId = Tools::getAdminGroupId($user->admin_id)[0];
        if ($groupId == Constant::$masterGroup) {
            $query->where(['t.status' => ['>', 0]]);
        } else {
            $query->where(['t.admin_id' => $user->admin_id]);
        }

        return $query->field("t.*,p.id as product_id,p.name,a.nickname")->select();
    }

    public static function getApply($id)
    {
        return ProductApply::get($id);
    }

    public static function getGift($type)
    {
        return Gift::where(['type' => $type, 'status' => 1])->select();
    }

    public static function getService($serviceId)
    {
        return ServiceLog::get($serviceId);
    }

    public static function getQuestions($type)
    {
        return Question::where(['type' => $type, 'status' => 1])->select();
    }

    public static function getUserCountTerminal($userId)
    {
        return Terminal::where(['user_id' => $userId])->count();
    }

    public static function getUserById($userId)
    {
        return User::where(['id' => $userId, 'status' => "normal"])->find();
    }

    public static function getFlow($id)
    {
        return FlowInfo::get($id);
    }

    public static function getFlowInfo($id)
    {
        return Db::name("flow_info")->alias("f")
            ->join("product p", "f.product_id = p.id", "left")
            ->where(['f.id' => $id])
            ->field("p.name,f.*")
            ->find();
    }

    public static function getApplyBySn($userId, $sn)
    {
        return ProductApply::where(['user_id' => $userId, "sn" => $sn, "status" => 1])->find();
    }

    public static function getApplyByUser($userId, $applyId)
    {
        return ProductApply::where(['user_id' => $userId, "id" => $applyId, "status" => 1])->find();
    }

    public static function getApplyList($userId)
    {
        $user = self::getUserById($userId);
        $query =  Db::name("product_apply")->alias("a")
            ->join("product p", "a.product_id = p.id", "left")
            ->where(["a.status" => ['>', 0]]);
        if ($user->group_id == 0) {
            $query->where(['a.user_id' => $userId]);
        }
        if ($user->group_id == Constant::$masterGroup) {
            $query->where(['a.confirm_time' => ['>', 0]]);
        }
        $sale = Tools::getGroupTree(Constant::$masterGroup, 4);
        if (count($sale) > 0 && in_array($user->group_id, $sale)) {
            $query->where(['a.confirm_time' => ['>', 0], 'admin_id' => $user->admin_id]);
        }
        return $query->field("a.id,p.name as product_name,a.sn,a.status,a.type,a.name,insert(a.phone , 4 , 4 , '****') as mobile,a.phone,
         a.address,a.admin_id,a.confirm_time,
         FROM_UNIXTIME(a.confirm_time, '%Y-%m-%d %H:%i:%s') as confirm_time_text,
         FROM_UNIXTIME(a.create_time, '%Y-%m-%d %H:%i:%s') as create_time,
         FROM_UNIXTIME(a.deliver_time, '%Y-%m-%d %H:%i:%s') as deliver_time")
            ->order('a.create_time desc')
            ->select();
    }

    public static function getProductById($productId)
    {
        return Product::get($productId);
    }

    public static function getBannerList()
    {
        return Banner::where(['status' => 1])->select();
    }

    public static function getTranDetails($sn, $table, $timeType)
    {
        if ($timeType == 1) {
            $date = date("Y-m-d");
            $format = "%Y-%m-%d";
        } elseif ($timeType == 2) {
            $date = date("Y-m");
            $format = "%Y-%m";
        } elseif ($timeType == 3) {
            $date = date("Y-m", strtotime("-1 month"));
            $format = "%Y-%m";
        }

        return Db::name($table)->alias("a")
            ->join("terminal t", "a.sn = t.sn", "left")
            ->join("product p", "p.id = t.product_id", "left")
            ->where(['a.sn' => $sn])
            ->where('FROM_UNIXTIME(trading_time,"' . $format . '") = "' . $date . '"')
            ->field("p.name,a.transaction_amount,FROM_UNIXTIME(a.trading_time, '%Y-%m-%d %H:%i:%s') as trading_time,a.transaction_rate")
            ->select();
    }

    public static function countTran($sn, $table, $date, $type = "d")
    {
        if ($type == "d") {
            $format = "%Y-%m-%d";
        } elseif ($type == "m") {
            $format = "%Y-%m";
        }

        return Db::name($table)->where(['sn' => $sn])->where('FROM_UNIXTIME(trading_time,"' . $format . '") = "' . $date . '"')->sum("transaction_amount");
    }

    public static function getUserTerminal($userId)
    {
        return Db::name("terminal")->alias("t")
            ->join("product p", "p.id = t.product_id", "left")
            ->where(['t.user_id' => $userId])
            ->select();
    }

    public static function getUserAddressByUser($userId)
    {
        return Address::where(['user_id' => $userId])->find();
    }

    public static function getUserAddressById($id)
    {
        return Address::get($id);
    }

    public static function getYsInfo($merchantId)
    {
        return YsInfo::where(['merchant_id' => $merchantId])->find();
    }

    //已操作流量卡统计
    public static function getFlowRewardHowMany($sn)
    {
        return FlowInfo::where(['sn' => $sn, 'status' => ['>', 0]])->find();
    }

    public static function getFlowBySn($sn)
    {
        return FlowInfo::where(['sn' => $sn])->find();
    }

    //终端扣除流量卡次数
    public static function getFlowHowMany($sn)
    {
        return FlowInfo::where(['sn' => $sn])->count();
    }

    public static function getProductList()
    {
        return Product::where(['status' => 1])->select();
    }

    public static function getTerminal($sn)
    {
        return Terminal::where(['sn' => $sn])->find();
    }

    /**
     * 查询验证码
     * @param $mobile
     * @return array|bool|false|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getSms($mobile)
    {
        return \app\common\model\SmsLogs::where(["sms_phone" => $mobile])->order("sms_create_time desc")->find();
    }
}
